#include "command_executor.h"
#include "service/backend_service.h"
#include "../database/database_manager.h"
#include "service/web_socket_server.h"
#include "open_url_file_command.h"
#include "commit_file_to_url_command.h"
#include "sync_disks_command.h"
#include "sync_folders_command.h"
#include "sync_root_folder_command.h"
#include "sync_files_command.h"
#include "get_notice_command.h"
#include "mark_read_notice_command.h"
#include "download_file_command.h"
#include "get_kms_file_by_file_id_command.h"
#include "rollback_file_command.h"
#include "delete_file_command.h"
#include "rename_file_command.h"
#include "rename_folder_command.h"
#include "delete_folder_command.h"
#include "commit_file_command.h"
#include "login_check_in_command.h"
#include "exchange_access_token_command.h"
#include <QDebug>
#include <QUuid>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QHttpMultiPart>
#include <QHttpPart>

// 静态成员变量初始化
QString CommandExecutor::m_accessToken;

CommandExecutor::CommandExecutor(QObject *parent)
    : QObject(parent)
    , m_backendService(nullptr)
    , m_databaseManager(nullptr)
    , m_webSocketServer(nullptr)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_openUrlFileCommand(new OpenUrlFileCommand(this))
    , m_commitFileToUrlCommand(new CommitFileToUrlCommand(this))
    , m_syncDisksCommand(new SyncDisksCommand(this))
    , m_syncFoldersCommand(new SyncFoldersCommand(this))
    , m_syncRootFolderCommand(new SyncRootFolderCommand(this))
    , m_syncFilesCommand(new SyncFilesCommand(this))
    , m_getNoticeCommand(new GetNoticeCommand(this))
    , m_markReadNoticeCommand(new MarkReadNoticeCommand(this))
    , m_downloadFileCommand(new DownloadFileCommand(this))
    , m_getKmsFileByFileIdCommand(new GetKmsFileByFileIdCommand(this))
    , m_rollbackFileCommand(new RollbackFileCommand(this))
    , m_deleteFileCommand(new DeleteFileCommand(this))
    , m_renameFileCommand(new RenameFileCommand(this))
    , m_renameFolderCommand(new RenameFolderCommand(this))
    , m_deleteFolderCommand(new DeleteFolderCommand(this))
    , m_commitFileCommand(new CommitFileCommand(this))
    , m_loginCheckinCommand(new LoginCheckinCommand(this))
    , m_exchangeAccessTokenCommand(new ExchangeAccessTokenCommand(this))
{
    // 连接 CommitFileToUrlCommand 的信号
    if (m_commitFileToUrlCommand) {
        connect(m_commitFileToUrlCommand, &CommitFileToUrlCommand::fileCommitCompleted,
                this, &CommandExecutor::fileCommitCompleted);
    }
    
    // 连接 SyncDisksCommand 的信号
    if (m_syncDisksCommand) {
        connect(m_syncDisksCommand, &SyncDisksCommand::syncDisksCompleted,
                this, &CommandExecutor::syncDisksCompleted);
    }
    
    // 连接 SyncFoldersCommand 的信号
    if (m_syncFoldersCommand) {
        connect(m_syncFoldersCommand, &SyncFoldersCommand::syncFoldersCompleted,
                this, &CommandExecutor::syncFoldersCompleted);
    }
    
    // 连接 SyncRootFolderCommand 的信号
    if (m_syncRootFolderCommand) {
        connect(m_syncRootFolderCommand, &SyncRootFolderCommand::syncRootFolderCompleted,
                this, &CommandExecutor::syncRootFolderCompleted);
    }
    
    // 连接 SyncFilesCommand 的信号
    if (m_syncFilesCommand) {
        connect(m_syncFilesCommand, &SyncFilesCommand::syncFilesCompleted,
                this, &CommandExecutor::syncFilesCompleted);
    }
    
    // 连接 GetNoticeCommand 的信号
    if (m_getNoticeCommand) {
        connect(m_getNoticeCommand, &GetNoticeCommand::getNoticeCompleted,
                this, &CommandExecutor::getNoticeCompleted);
    }
    
    // 连接 MarkReadNoticeCommand 的信号
    if (m_markReadNoticeCommand) {
        connect(m_markReadNoticeCommand, &MarkReadNoticeCommand::markReadNoticeCompleted,
                this, &CommandExecutor::markReadNoticeCompleted);
    }
    
    // 连接 DownloadFileCommand 的信号
    if (m_downloadFileCommand) {
        connect(m_downloadFileCommand, &DownloadFileCommand::downloadFileCompleted,
                this, &CommandExecutor::downloadFileCompleted);
        connect(m_downloadFileCommand, &DownloadFileCommand::downloadProgress,
                this, &CommandExecutor::downloadProgress);
    }
    
    // 连接 GetKmsFileByFileIdCommand 的信号
    if (m_getKmsFileByFileIdCommand) {
        connect(m_getKmsFileByFileIdCommand, &GetKmsFileByFileIdCommand::getKmsFileByFileIdCompleted,
                this, &CommandExecutor::getKmsFileByFileIdCompleted);
    }
    
    // 连接 RollbackFileCommand 的信号
    if (m_rollbackFileCommand) {
        connect(m_rollbackFileCommand, &RollbackFileCommand::rollbackFileCompleted,
                this, &CommandExecutor::rollbackFileCompleted);
    }
    
    // 连接 DeleteFileCommand 的信号
    if (m_deleteFileCommand) {
        connect(m_deleteFileCommand, &DeleteFileCommand::deleteFileCompleted,
                this, &CommandExecutor::deleteFileCompleted);
    }
    
    // 连接 RenameFileCommand 的信号
    if (m_renameFileCommand) {
        connect(m_renameFileCommand, &RenameFileCommand::renameFileCompleted,
                this, &CommandExecutor::renameFileCompleted);
    }
    
    // 连接 RenameFolderCommand 的信号
    if (m_renameFolderCommand) {
        connect(m_renameFolderCommand, &RenameFolderCommand::renameFolderCompleted,
                this, &CommandExecutor::renameFolderCompleted);
    }
    
    // 连接 DeleteFolderCommand 的信号
    if (m_deleteFolderCommand) {
        connect(m_deleteFolderCommand, &DeleteFolderCommand::deleteFolderCompleted,
                this, &CommandExecutor::deleteFolderCompleted);
    }
    
    // 连接 CommitFileCommand 的信号
    if (m_commitFileCommand) {
        connect(m_commitFileCommand, &CommitFileCommand::commitFileCompleted,
                this, &CommandExecutor::commitFileCompleted);
    }
    
    // 连接 LoginCheckinCommand 的信号
    if (m_loginCheckinCommand) {
        connect(m_loginCheckinCommand, &LoginCheckinCommand::loginResult,
                this, &CommandExecutor::loginResult);
        connect(m_loginCheckinCommand, &LoginCheckinCommand::userWorkDirectoryCreated,
                this, &CommandExecutor::userWorkDirectoryCreated);
    }
    
    // 连接 ExchangeAccessTokenCommand 的信号
    if (m_exchangeAccessTokenCommand) {
        // 连接信号到内部处理槽，处理后发出对外信号并触发同步网盘
        connect(m_exchangeAccessTokenCommand, &ExchangeAccessTokenCommand::exchangeAccessTokenCompleted,
                this, &CommandExecutor::handleExchangeAccessTokenCompleted);
    }
    
    // 设置 NetworkAccessManager
    setNetworkAccessManager();
}

void CommandExecutor::setBackendService(BackendService *backendService)
{
    m_backendService = backendService;
    // 同时设置给 OpenUrlFileCommand、CommitFileToUrlCommand 和 SyncDisksCommand
    if (m_openUrlFileCommand) {
        m_openUrlFileCommand->setBackendService(backendService);
    }
    if (m_commitFileToUrlCommand) {
        m_commitFileToUrlCommand->setBackendService(backendService);
    }
    if (m_syncDisksCommand) {
        m_syncDisksCommand->setBackendService(backendService);
        m_syncDisksCommand->setCommandExecutor(this); // 设置 CommandExecutor 引用，用于调用 executeSyncFolders
    }
    if (m_syncFoldersCommand) {
        m_syncFoldersCommand->setBackendService(backendService);
    }
    if (m_syncRootFolderCommand) {
        m_syncRootFolderCommand->setBackendService(backendService);
    }
    if (m_syncFilesCommand) {
        m_syncFilesCommand->setBackendService(backendService);
    }
    if (m_getNoticeCommand) {
        m_getNoticeCommand->setBackendService(backendService);
    }
    if (m_markReadNoticeCommand) {
        m_markReadNoticeCommand->setBackendService(backendService);
    }
    if (m_downloadFileCommand) {
        m_downloadFileCommand->setBackendService(backendService);
    }
    if (m_getKmsFileByFileIdCommand) {
        m_getKmsFileByFileIdCommand->setBackendService(backendService);
    }
    if (m_rollbackFileCommand) {
        m_rollbackFileCommand->setBackendService(backendService);
        m_rollbackFileCommand->setCommandExecutor(this); // 设置 CommandExecutor 引用，用于调用 executeDownloadFile
    }
    if (m_deleteFileCommand) {
        m_deleteFileCommand->setBackendService(backendService);
    }
    if (m_renameFileCommand) {
        m_renameFileCommand->setBackendService(backendService);
    }
    if (m_renameFolderCommand) {
        m_renameFolderCommand->setBackendService(backendService);
    }
    if (m_deleteFolderCommand) {
        m_deleteFolderCommand->setBackendService(backendService);
    }
    if (m_commitFileCommand) {
        m_commitFileCommand->setBackendService(backendService);
    }
    if (m_loginCheckinCommand) {
        m_loginCheckinCommand->setBackendService(backendService);
    }
    if (m_exchangeAccessTokenCommand) {
        m_exchangeAccessTokenCommand->setBackendService(backendService);
    }
}

void CommandExecutor::setDatabaseManager(DatabaseManager *databaseManager)
{
    m_databaseManager = databaseManager;
    // 同时设置给 OpenUrlFileCommand、CommitFileToUrlCommand 和 SyncDisksCommand
    if (m_openUrlFileCommand) {
        m_openUrlFileCommand->setDatabaseManager(databaseManager);
    }
    if (m_commitFileToUrlCommand) {
        m_commitFileToUrlCommand->setDatabaseManager(databaseManager);
    }
    if (m_syncDisksCommand) {
        m_syncDisksCommand->setDatabaseManager(databaseManager);
    }
    if (m_syncFoldersCommand) {
        m_syncFoldersCommand->setDatabaseManager(databaseManager);
    }
    if (m_syncRootFolderCommand) {
        m_syncRootFolderCommand->setDatabaseManager(databaseManager);
    }
    if (m_syncFilesCommand) {
        m_syncFilesCommand->setDatabaseManager(databaseManager);
    }
    // GetNoticeCommand 和 MarkReadNoticeCommand 不需要 DatabaseManager
    if (m_downloadFileCommand) {
        m_downloadFileCommand->setDatabaseManager(databaseManager);
    }
    // GetKmsFileByFileIdCommand 不需要 DatabaseManager
    if (m_rollbackFileCommand) {
        m_rollbackFileCommand->setDatabaseManager(databaseManager);
    }
    if (m_deleteFileCommand) {
        m_deleteFileCommand->setDatabaseManager(databaseManager);
    }
    if (m_renameFileCommand) {
        m_renameFileCommand->setDatabaseManager(databaseManager);
    }
    if (m_renameFolderCommand) {
        m_renameFolderCommand->setDatabaseManager(databaseManager);
    }
    if (m_deleteFolderCommand) {
        m_deleteFolderCommand->setDatabaseManager(databaseManager);
    }
    if (m_commitFileCommand) {
        m_commitFileCommand->setDatabaseManager(databaseManager);
    }
    if (m_loginCheckinCommand) {
        m_loginCheckinCommand->setDatabaseManager(databaseManager);
    }
    if (m_exchangeAccessTokenCommand) {
        m_exchangeAccessTokenCommand->setDatabaseManager(databaseManager);
    }
}

void CommandExecutor::setNetworkAccessManager()
{
    // 设置 NetworkAccessManager 给 OpenUrlFileCommand、CommitFileToUrlCommand 和 SyncDisksCommand
    if (m_openUrlFileCommand) {
        m_openUrlFileCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_commitFileToUrlCommand) {
        m_commitFileToUrlCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_syncDisksCommand) {
        m_syncDisksCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_syncFoldersCommand) {
        m_syncFoldersCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_syncRootFolderCommand) {
        m_syncRootFolderCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_syncFilesCommand) {
        m_syncFilesCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_getNoticeCommand) {
        m_getNoticeCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_markReadNoticeCommand) {
        m_markReadNoticeCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_downloadFileCommand) {
        m_downloadFileCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_getKmsFileByFileIdCommand) {
        m_getKmsFileByFileIdCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_rollbackFileCommand) {
        m_rollbackFileCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_deleteFileCommand) {
        m_deleteFileCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_renameFileCommand) {
        m_renameFileCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_renameFolderCommand) {
        m_renameFolderCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_deleteFolderCommand) {
        m_deleteFolderCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_commitFileCommand) {
        m_commitFileCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_loginCheckinCommand) {
        m_loginCheckinCommand->setNetworkAccessManager(m_networkManager);
    }
    if (m_exchangeAccessTokenCommand) {
        m_exchangeAccessTokenCommand->setNetworkAccessManager(m_networkManager);
    }
}

QNetworkAccessManager* CommandExecutor::getNetworkAccessManager() const
{
    return m_networkManager;
}

void CommandExecutor::setWebSocketServer(WebSocketServer *webSocketServer)
{
    m_webSocketServer = webSocketServer;
    // 同时设置给 CommitFileToUrlCommand
    if (m_commitFileToUrlCommand) {
        m_commitFileToUrlCommand->setWebSocketServer(webSocketServer);
    }
}

bool CommandExecutor::executeOpenUrlFileCommand(const QJsonObject &jsonObj)
{
    if (!m_openUrlFileCommand) {
        qDebug() << "OpenUrlFileCommand 未初始化，无法执行命令";
        return false;
    }
    
    if (!m_databaseManager) {
        qDebug() << "DatabaseManager 未设置，无法保存命令记录";
        return false;
    }
    
    // 创建命令记录
    KmsCommand cmd;
    cmd.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
    cmd.command = "openurlfile";
    
    // 构建 PARAMS JSON
    QString downloadUrl = jsonObj.value("downloadurl").toString();
    QString commitUrl = jsonObj.value("commiturl").toString();
    QString accessToken = jsonObj.value("accesstoken").toString();
    
    QJsonObject paramsObj;
    if (!downloadUrl.isEmpty()) {
        paramsObj["DOWNLOAD_URL"] = downloadUrl;
    }
    if (!commitUrl.isEmpty()) {
        paramsObj["COMMIT_URL"] = commitUrl;
    }
    if (!accessToken.isEmpty()) {
        paramsObj["ACCESS_TOKEN"] = accessToken;
    }
    
    QJsonDocument jsonDoc(paramsObj);
    cmd.params = jsonDoc.toJson(QJsonDocument::Compact);
    
    QString currentDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    cmd.createDate = currentDateTime;
    cmd.lastModifyDate = currentDateTime;
    cmd.status = "PENDING"; // 待处理

    // 插入数据库
    if (!m_databaseManager->insertCommand(cmd)) {
        qDebug() << QString("插入命令记录到数据库失败，命令: %1").arg(cmd.command);
        return false;
    }
    
    qDebug() << QString("成功插入命令记录到数据库，命令: %1, ID: %2").arg(cmd.command, cmd.id);
    
    // 使用成员变量 OpenUrlFileCommand 执行命令
    return m_openUrlFileCommand->execute(jsonObj);
}


void CommandExecutor::executeCommitFileToUrl(const QString &filePath)
{
    if (!m_databaseManager) {
        qDebug() << "CommandExecutor: 数据库管理器未设置，无法查询命令记录";
        return;
    }
    
    // 统一路径分隔符，确保匹配正确
    QString normalizedPath = QDir::cleanPath(filePath);
    normalizedPath = normalizedPath.replace('\\', '/');
    
    qDebug() << "CommandExecutor: 处理文件删除事件，文件路径:" << normalizedPath;
    
    // 在 kms_command 表中查找匹配的命令记录
    // 使用尾部匹配查找 LOCAL_FILE_PATH，并添加条件 command='commitfiletourl'
    // 注意：kms_command.local_file_path 存放为完整路径，所以使用尾部匹配
    KmsCommand command = m_databaseManager->queryCommandByLocalFilePathAndCommand(normalizedPath, "commitfiletourl");
    
    if (command.id.isEmpty()) {
        qDebug() << "CommandExecutor: 未找到匹配的命令记录，文件路径:" << normalizedPath;
        return;
    }
    
    // 从 PARAMS JSON 中解析参数
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(command.params.toUtf8(), &parseError);
    QString commitUrl, localFilePath, accessToken;
    
    if (parseError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
        QJsonObject paramsObj = jsonDoc.object();
        commitUrl = paramsObj.value("COMMIT_URL").toString();
        localFilePath = paramsObj.value("LOCAL_FILE_PATH").toString();
        accessToken = paramsObj.value("ACCESS_TOKEN").toString();
    }
    
    qDebug() << "CommandExecutor: 找到匹配的命令记录，ID:" << command.id 
             << "命令:" << command.command
             << "提交URL:" << commitUrl
             << "文件地址:" << localFilePath;
    
    // 使用从 PARAMS JSON 解析出的 commitUrl 提交位于 localFilePath 的文件
    if (!commitUrl.isEmpty() && !localFilePath.isEmpty()) {
        qDebug() << "CommandExecutor: 开始提交文件，URL:" << commitUrl 
                 << "文件路径:" << localFilePath
                 << "accessToken:" << (accessToken.isEmpty() ? "空" : "已提供");
        
        if (!m_commitFileToUrlCommand) {
            qDebug() << "CommandExecutor: CommitFileToUrlCommand 未初始化，无法执行命令";
            return;
        }
        
        // 确保网络管理器已设置
        if (m_commitFileToUrlCommand) {
            m_commitFileToUrlCommand->setNetworkAccessManager(m_networkManager);
        }

        // 执行命令（响应由 CommitFileToUrlCommand::handleUploadResponse 处理）
        bool success = m_commitFileToUrlCommand->execute(commitUrl, localFilePath, accessToken);

        // 如果同步执行失败，发出错误信号
        if (!success) {
            emit fileCommitCompleted(-1, "文件提交请求失败");
        }

    } else {
        qDebug() << "CommandExecutor: 命令记录缺少提交URL或文件路径";
        if (commitUrl.isEmpty()) {
            qDebug() << "CommandExecutor: 提交URL为空";
        }
        if (localFilePath.isEmpty()) {
            qDebug() << "CommandExecutor: 文件路径为空";
        }
    }
}

bool CommandExecutor::executeSyncDisks()
{
    if (!m_syncDisksCommand) {
        qDebug() << "CommandExecutor: SyncDisksCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行同步网盘命令";
    
    // 使用成员变量 SyncDisksCommand 执行命令
    return m_syncDisksCommand->execute();
}

bool CommandExecutor::executeSyncFolders(const QString &diskId)
{
    if (!m_syncFoldersCommand) {
        qDebug() << "CommandExecutor: SyncFoldersCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行同步文件夹命令，网盘ID:" << diskId;
    
    // 使用成员变量 SyncFoldersCommand 执行命令
    return m_syncFoldersCommand->execute(diskId);
}

bool CommandExecutor::executeSyncRootFolder(const QString &diskId)
{
    if (!m_syncRootFolderCommand) {
        qDebug() << "CommandExecutor: SyncRootFolderCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行同步根文件夹命令，网盘ID:" << diskId;
    
    // 使用成员变量 SyncRootFolderCommand 执行命令
    return m_syncRootFolderCommand->execute(diskId);
}

bool CommandExecutor::executeSyncFiles(const QString &folderId)
{
    if (!m_syncFilesCommand) {
        qDebug() << "CommandExecutor: SyncFilesCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行同步文件命令，文件夹ID:" << folderId;
    
    // 使用成员变量 SyncFilesCommand 执行命令
    return m_syncFilesCommand->execute(folderId);
}

bool CommandExecutor::executeGetNotice(int readStatus, int type, int currpage, int rowcount)
{
    if (!m_getNoticeCommand) {
        qDebug() << "CommandExecutor: GetNoticeCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行获取通知命令，readStatus:" << readStatus 
             << "type:" << type << "currpage:" << currpage << "rowcount:" << rowcount;
    
    // 使用成员变量 GetNoticeCommand 执行命令
    return m_getNoticeCommand->execute(readStatus, type, currpage, rowcount);
}

bool CommandExecutor::executeMarkReadNotice(const QString &noticeId)
{
    if (!m_markReadNoticeCommand) {
        qDebug() << "CommandExecutor: MarkReadNoticeCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行标记已读通知命令，通知ID:" << noticeId;
    
    // 使用成员变量 MarkReadNoticeCommand 执行命令
    return m_markReadNoticeCommand->execute(noticeId);
}

bool CommandExecutor::executeDownloadFile(const QString &url, const QString &fileName, const QString &fileId)
{
    if (!m_downloadFileCommand) {
        qDebug() << "CommandExecutor: DownloadFileCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行下载文件命令，URL:" << url << "文件名:" << fileName << "文件ID:" << fileId;
    
    // 使用成员变量 DownloadFileCommand 执行命令
    return m_downloadFileCommand->execute(url, fileName, fileId);
}

bool CommandExecutor::executeGetKmsFileByFileId(const QString &fileId)
{
    if (!m_getKmsFileByFileIdCommand) {
        qDebug() << "CommandExecutor: GetKmsFileByFileIdCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行通过文件ID获取KmsFile命令，文件ID:" << fileId;
    
    // 使用成员变量 GetKmsFileByFileIdCommand 执行命令
    return m_getKmsFileByFileIdCommand->execute(fileId);
}

bool CommandExecutor::executeRollbackFile(const QString &fileId)
{
    if (!m_rollbackFileCommand) {
        qDebug() << "CommandExecutor: RollbackFileCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行回撤文件命令，文件ID:" << fileId;
    
    // 使用成员变量 RollbackFileCommand 执行命令
    return m_rollbackFileCommand->execute(fileId);
}

bool CommandExecutor::executeDeleteFile(const QString &fileId)
{
    if (!m_deleteFileCommand) {
        qDebug() << "CommandExecutor: DeleteFileCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行删除文件命令，文件ID:" << fileId;
    
    // 使用成员变量 DeleteFileCommand 执行命令
    return m_deleteFileCommand->execute(fileId);
}

bool CommandExecutor::executeRenameFile(const QString &fileId, const QString &newName)
{
    if (!m_renameFileCommand) {
        qDebug() << "CommandExecutor: RenameFileCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行重命名文件命令，文件ID:" << fileId << "新文件名:" << newName;
    
    // 使用成员变量 RenameFileCommand 执行命令
    return m_renameFileCommand->execute(fileId, newName);
}

bool CommandExecutor::executeRenameFolder(const QString &folderId, const QString &newName)
{
    if (!m_renameFolderCommand) {
        qDebug() << "CommandExecutor: RenameFolderCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行重命名文件夹命令，文件夹ID:" << folderId << "新文件夹名:" << newName;
    
    // 使用成员变量 RenameFolderCommand 执行命令
    return m_renameFolderCommand->execute(folderId, newName);
}

bool CommandExecutor::executeDeleteFolder(const QString &folderId)
{
    if (!m_deleteFolderCommand) {
        qDebug() << "CommandExecutor: DeleteFolderCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行删除文件夹命令，文件夹ID:" << folderId;
    
    // 使用成员变量 DeleteFolderCommand 执行命令
    return m_deleteFolderCommand->execute(folderId);
}

bool CommandExecutor::executeCommitFile(const QString &diskId, const QString &folderId, const QString &sourceFileId)
{
    if (!m_commitFileCommand) {
        qDebug() << "CommandExecutor: CommitFileCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行提交文件命令，网盘ID:" << diskId << "文件夹ID:" << folderId << "源文件ID:" << sourceFileId;
    
    // 使用成员变量 CommitFileCommand 执行命令
    return m_commitFileCommand->execute(diskId, folderId, sourceFileId);
}

bool CommandExecutor::executeLoginCheckin(const QString &username, const QString &password, const QString &checkcode)
{
    if (!m_loginCheckinCommand) {
        qDebug() << "CommandExecutor: LoginCheckinCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行登录检查命令，用户名:" << username;
    
    // 使用成员变量 LoginCheckinCommand 执行命令
    return m_loginCheckinCommand->execute(username, password, checkcode);
}

bool CommandExecutor::executeExchangeAccessToken()
{
    if (!m_exchangeAccessTokenCommand) {
        qDebug() << "CommandExecutor: ExchangeAccessTokenCommand 未初始化，无法执行命令";
        return false;
    }
    
    qDebug() << "CommandExecutor: 执行交换AccessToken命令（domainId 将在方法内部获取）";
    
    // 使用成员变量 ExchangeAccessTokenCommand 执行命令
    return m_exchangeAccessTokenCommand->execute();
}

QString CommandExecutor::getAccessToken()
{
    qDebug() << "CommandExecutor: 获取访问令牌:" << m_accessToken;
    return m_accessToken;
}

void CommandExecutor::setAccessToken(const QString &accessToken)
{
    m_accessToken = accessToken;
    qDebug() << "CommandExecutor: 设置访问令牌:" << accessToken;
}

void CommandExecutor::handleExchangeAccessTokenCompleted(int resultCode, const QString &message, const QString &accessToken)
{
    // 先发出对外信号，供外部（如QML）监听
    emit exchangeAccessTokenCompleted(resultCode, message, accessToken);
    
    // 当 ExchangeAccessTokenCommand 执行成功时，触发同步网盘
    if (resultCode == 0 && !accessToken.isEmpty()) {
        qDebug() << "CommandExecutor: ExchangeAccessTokenCommand 执行成功，触发同步网盘";
        executeSyncDisks();
    } else {
        qDebug() << "CommandExecutor: ExchangeAccessTokenCommand 执行失败，不触发同步网盘，resultCode:" << resultCode;
    }
}

